/**************************************************************
  > File Name: myshell.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2022年01月29日 星期六 11时24分58秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/wait.h>
#include <glob.h>

#define DELIMS " \n\t"

struct cmd_t
{
	glob_t globres;
};

static void prompt(void)
{
	printf("ll@ubuntu: ");
}

static void parse(char *buf, struct cmd_t *res)
{
	char *tok = NULL;
	int i = 0;

	while (1)
	{
		tok = strsep(&buf,DELIMS);
		if (tok == NULL)
			break;
		if (tok[0] == '\0')
			continue;
		glob(tok, GLOB_NOCHECK | (GLOB_APPEND * i), NULL, &res->globres);
		i = 1;
	}
}

int main(int argc, char **argv)
{
	char *lineBuf = NULL;
	size_t lineSize = 0;
	pid_t pid;
	struct cmd_t cmd;

	while (1)
	{
		prompt();

		if (getline(&lineBuf, &lineSize, stdin) < 0)
		{
			break;
		}

		parse(lineBuf, &cmd);

		if (0)
		{
		}
		else
		{
			pid = fork();
			if (pid < 0)
			{
				perror("fork()");
				exit(1);
			}
			else if (pid == 0)
			{
				execvp(cmd.globres.gl_pathv[0], cmd.globres.gl_pathv);
				perror("execvp()");
				exit(1);
			}
			wait(NULL);
		}
	}

    exit(0);
}
